/*
 * Copyright 2009 Douglas Lockamy, dlockamy_at_gmail.com
 * All rights reserved. Distributed under the terms of the MIT License.
 */
/*
    message spec
    
    Message is write only, an app writes where:
    
    path = mime name of application to receive message
    buffer = message to be transfered to application
    
    messagefs.tick() connects to cthulhu server, receives pending messages,
        posts them to file paths via write calls.

*/
if (!this.messagefs) messagefs = {};
message_vfsNode.item=messagefs;
messagefs.version = '0.1';

messagefs.sessionHash;
messagefs.username;




messagefs.tick = function()
{
    cthulhuURL = "php_proxy.php?username="+messagefs.username+"&hash="+messagefs.sessionKey+"&function_id=01";

    benix.ajaxObj.open("GET",cthulhuURL,false);
    benix.ajaxObj.send(null);
       
    if(benix.ajaxObj.responseText != 'FAIL' )
    {
        messagefs.process( benix.ajaxObj.responseText );
    }   
    else
        return -1;

    return 0;
};

messagefs.init = function()
{
    //benix.registerTick(messagefs.tick() );
};

messagefs.ajaxObj = new benix.ajaxBuilder();

messagefs.mount = function(serverAddress,fs_type,mountPoint,user,pass,argv)
{
    loginURL = "php_proxy.php/?username="+user+"&pass="+pass;

    messagefs.ajaxObj.open("GET",loginURL,false);
    messagefs.ajaxObj.send(null);
      
    if(messagefs.ajaxObj.responseText != 'FAIL' && messagefs.ajaxObj.responseText != "")
    {
        messagefs.sessionHash = benix.ajaxObj.responseText;
        messagefs.username = user;
        return 1;
    }   
    else
    {
        alert("messagefs login failed "+messagefs.ajaxObj.responseText);
        return -1;
    }

    return 0;
};

messagefs.umount = function(mountPoint)
{
    return 0;
};

messagefs.read = function(path,flags,buffer,offset,length,sessionKey)
{
    return -1;
};

messagefs.write = function(path,flags,buffer,offset,length,sessionKey)
{
    var workPath = '/';
    var aNode = 0;
    var pathArray = path.split('/');
    var counter=0;
    
    while(counter <= pathArray.length-2)
    {
        if(workPath == '/')
            workPath = workPath + pathArray[counter];
        else
            workPath = workPath + '/' + pathArray[counter];
        counter++;
    }

    if(flags==0)
    {
        return -1; 
    }
    
    if(flags==1)
    {
            return -1;
    }
    else if(flags==2)
    {
    /*
        search for app of mime type 'path' and write message 'buffer'
        if(aNode.Type==5 )
        {
            var loadPath = benix.fsBuildMountPath(aNode,path);

            return(aNode.Data[3].write(loadPath,flags,buffer) );
        }  
        
        else*/
            return -1;
    }
    else if(flags==3)
    {
        return -1; 
    }
    else 
        return -1;

};

messagefs.process = function( responseText )
{
    benix.stdout("messagefs.process()");
};
